package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description: 获取博客详情页的中博客的用户信息
 */
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        String para = req.getParameter("blogId");
        if(para == null || "".equals(para)) {
            resp.getWriter().write("{\"ok\": false, \"reason\": \"参数缺失!\" }");
            return;
        }

        // 根据 blogId 查询 blog 信息
        int blogId = Integer.parseInt(para);
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectBlog(blogId);
        if(blog == null) {
            resp.getWriter().write("{\"ok\": false, \"reason\": \"查询的博客不存在!\" }");
            return;
        }

        // 根据 blog 获取 userId，并获得user对象
        int userId = blog.getUserId();
        UserDao userDao = new UserDao();
        User user = userDao.selectById(userId);
        if(user == null) {
            resp.getWriter().write("{\"ok\": false, \"reason\": \"查询的用户不存在!\" }");
            return;
        }
        // 将 user 的密码置为null并转成JSON格式并写入响应
        user.setPassWord(null);
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
